﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Base;
using DevExpress.XtraCharts;
using System.Collections;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Drawing;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Data.SqlClient;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Project_Progress : frmBaseChild
    {
        public frmMES_Project_Progress()
        {
            InitializeComponent();
        }

        private void frmMES_Project_Progress_Resize(object sender, EventArgs e)
        {
            //防止主窗体最小化时报错
            try
            {
                splitContainer1.SplitterDistance = splitContainer1.Width * 3 / 5;
            }
            catch(Exception ex)
            {
            }
        }

        private void frmMES_Project_Progress_Load(object sender, EventArgs e)
        {
            //只刷新未完成数，无负责人，完成日期为空
            string strSql = @"SELECT Owner AS Leader
							FROM [Sys_TestManage_Record]
							WHERE Owner IS NOT NULL AND Update_TS IS NULL
							UNION
							SELECT Owner COLLATE Chinese_PRC_CI_AS
							FROM [Lamex_Project_Manager].[dbo].[MAPPLYINFO]
							WHERE  Owner IS NOT NULL AND Actual_TS IS NULL
							ORDER BY Leader";
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            //comboBoxLeader.DataSource = dt;
            //comboBoxLeader.DisplayMember = "Leader";

            //额外加下拉选项
            ArrayList list = new ArrayList();
            list.Add("");
            list.Add("全部");

            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr[0].ToString().Trim());
            }

            comboBoxLeader.DataSource = list;
            //comboBoxLeader.Text = "";

        }

        private void comboBoxLeader_SelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBoxLeader.Text.ToString() == "")
            {
                return;
            }
            else if (comboBoxLeader.Text.ToString() == "全部")
            {
                refreshGridView("1=1");
                refreshChartView("1=1");
            }
            else
            {
                refreshGridView("Owner='" + comboBoxLeader.Text.ToString() + @"'");
                refreshChartView("Owner='" + comboBoxLeader.Text.ToString() + @"'");
            }

            gridView1.Columns["进度"].DisplayFormat.FormatType = FormatType.Numeric;
            gridView1.Columns["进度"].DisplayFormat.FormatString = "p0";
            CustomProgressBarColumn(gridView1, "进度", 50, Brushes.IndianRed, Brushes.DodgerBlue);
            gridView1.Columns["提出日期"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            //refreshGridView("Leader='" + comboBoxLeader.Text.ToString() + @"'");
            //refreshChartView();
        }

        private void buttonInput_Click(object sender, EventArgs e)
        {
            string strSql;
            string CurUser = Lamex.Common.Loginer.CurrentUser.Account;//导入用户
            string CurTime = System.DateTime.Now.ToString();

            //更新【申请项目】
            strSql = @"INSERT INTO [LamexMESManager].[dbo].[PJT_Project_Progess]
                        SELECT DISTINCT 'A' + Apply_NO,Owner,0,,NULL,GETDATE(),'" + CurUser + @"'
                        FROM [Lamex_Project_Manager].[dbo].[MAPPLYINFO] AS a
                        LEFT JOIN
                        [LamexMESManager].[dbo].[PJT_Project_Progess] AS b 
                        ON 'A' + a.Apply_NO COLLATE Chinese_PRC_CI_AS = b.Project_No COLLATE Chinese_PRC_CI_AS
                        WHERE Owner IS NOT NULL AND Project_No IS NULL";
            BaseBuildSql.ExecuteNonQuery(strSql);

            //更新【测试项目】
            strSql = @"INSERT INTO PJT_Project_Progess
                        SELECT DISTINCT 'T' + CAST(IDNO AS VARCHAR),Owner,0,NULL,GETDATE(),'" + CurUser + @"'
                        FROM Sys_TestManage_Record AS a
                        LEFT JOIN
                        PJT_Project_Progess AS b 
                        ON 'T' + CAST(a.IDNO AS VARCHAR) = b.Project_No
                        WHERE Owner IS NOT NULL AND Project_No IS NULL";
            BaseBuildSql.ExecuteNonQuery(strSql);

            comboBoxLeader.Text = "全部";
            refreshGridView("1=1");//全部刷新
            refreshChartView("1=1");

            //记录导入数据条数并反馈给用户
            //MessageBox.Show("");
        }

        private void refreshGridView(string strVar)
        {
            //只刷新未完成数，无负责人，完成日期为空
            string strSql = @"SELECT 编号,负责,协助,提出,b.Complete_Percent AS 进度,提出日期,完成日期,项目描述
								FROM
								(SELECT 'A' + Apply_NO COLLATE Chinese_PRC_CI_AS AS 编号,
                                Owner COLLATE Chinese_PRC_CI_AS AS 负责,
                                Owner2 COLLATE Chinese_PRC_CI_AS AS 协助,
                                ApplyName COLLATE Chinese_PRC_CI_AS AS 提出,
                                Apply_TS AS 提出日期,
                                Actual_TS AS 完成日期,
                                Apply_DEC COLLATE Chinese_PRC_CI_AS AS 项目描述
                                FROM [Lamex_Project_Manager].[dbo].[MAPPLYINFO]                                
                                WHERE Owner IS NOT NULL AND Actual_TS IS NULL AND " + strVar + @"
                                UNION
                                SELECT 'T' + CAST(IDNO AS varchar),Owner,NULL,C_User,C_TS,Update_TS,Desc_Question
                                FROM [LamexMESManager].[dbo].[Sys_TestManage_Record]
                                WHERE Owner IS NOT NULL AND Update_TS IS NULL AND " + strVar + @") AS a
                                LEFT JOIN [LamexMESManager].[dbo].[PJT_Project_Progess] AS b
								ON a.编号=b.Project_No";
            
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            //gridView1.Columns.Clear();
            gridControl1.DataSource = dt;

            //gridView1.BestFitColumns();
            gridView1.Columns[0].BestFit();
            gridView1.Columns[1].BestFit();
            gridView1.Columns[2].BestFit();
            //gridView1.Columns[3].BestFit();
            gridView1.Columns[3].Width = 100;
            gridView1.Columns[4].BestFit();
            gridView1.Columns[5].BestFit();
            gridView1.Columns[6].BestFit();

            setGridViewEditaleColumn();
            setTotalSum();
        }

        //设置可编辑数据列，设置特定列可编辑，必须在加载数据后执行
        private void setGridViewEditaleColumn()
        {
            gridView1.OptionsBehavior.Editable = true;
            gridView1.OptionsBehavior.ReadOnly = false;

            foreach (GridColumn c in gridView1.Columns)
            {
                if (c.Name == "col进度")
                {
                    c.OptionsColumn.ReadOnly = false;
                    c.OptionsColumn.AllowEdit = true;
                }
                else
                {
                    c.OptionsColumn.ReadOnly = true;
                    c.OptionsColumn.AllowEdit = false;
                }
            }
        }

        private void refreshChartView(string strVar)
        {
            //只刷新未完成数，无负责人，完成日期为空
            //UNION时一定要加ALL参数，否则当两个表取数Owner与QTY相同情况下，会导致QTY只有1/2（只统计一张表）
            string strSql = @"SELECT Leader,SUM(QTY) AS QTY
							FROM
							(SELECT Owner AS Leader,COUNT(Owner) AS QTY
							FROM [Sys_TestManage_Record]
							WHERE Owner IS NOT NULL AND Update_TS IS NULL AND " + strVar + @"
							GROUP BY Owner
							UNION ALL
							SELECT Owner COLLATE Chinese_PRC_CI_AS,COUNT(Owner) AS QTY
							FROM [Lamex_Project_Manager].[dbo].[MAPPLYINFO]
							WHERE  Owner IS NOT NULL AND Actual_TS IS NULL AND " + strVar + @"
							GROUP BY Owner COLLATE Chinese_PRC_CI_AS) AS a
							GROUP BY Leader";
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            
            chartControl1.Series.Clear();

            if (dt.Rows.Count != 0)
            {
                //Series series1 = new Series("", ViewType.Line);
                Series series1 = new Series("", ViewType.Bar);

                foreach (DataRow dr in dt.Rows)
                {
                    SeriesPoint p = new SeriesPoint();

                    double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr["QTY"].ToString())), 2).ToString()) };
                    p.Values = d;
                    p.Argument = dr["Leader"].ToString();
                    series1.Points.Add(p);
                }

                chartControl1.Series.Add(series1);
                chartControl1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
                Legend Legends = (Legend)chartControl1.Legend;
                Legends.Visibility = DevExpress.Utils.DefaultBoolean.True;
                Legends.AlignmentVertical = LegendAlignmentVertical.Top;
                Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
                Legends.TextVisible = true;

                //强制显示所有x轴标签
                XYDiagram diagram = ((XYDiagram)chartControl1.Diagram);
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagram.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;

                //设置Series的标签
                series1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据

                //设置标签的显示位置
                SideBySideBarSeriesLabel label = (SideBySideBarSeriesLabel)series1.Label;
                label.Position = BarSeriesLabelPosition.Top;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {

        }

        //gridView仅复制单元格内容，复制选中行焦点单元格的值
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gridView1.GetFocusedRowCellValue(gridView1.FocusedColumn));
                e.Handled = true;
            }

            //或设置属性
            //optionBehavior - CopyToClipboardWithColumnHeader = false;
            //optionSelection - MultiSelectMode = CellSelect;
        }

        /// <summary>
        /// 此为自定义进度条列（根据值范围填充不同颜色）
        /// 不加范围限制（填充相同颜色）方法：Run Designer-添加并绑定Columns-ColumnEdit设为repositoryItemProgressBar
        /// 根据需要在In-place Editor Repository中设置repositoryItemProgressBar1属性即可
        /// </summary>
        /// <param name="view"></param>
        /// <param name="fieldName">列的字段名</param>
        /// <param name="warningValue"></param>
        /// <param name="lessColor"></param>
        /// <param name="greaterColor"></param>
        public static void CustomProgressBarColumn(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName, int warningValue = 50, Brush lessColor = null, Brush greaterColor = null)
        {
            var col = view.Columns[fieldName];
            if (col == null) return;

            col.AppearanceCell.Options.UseTextOptions = true;

            col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            view.CustomDrawCell += (s, e) =>
            {
                if (e.Column.FieldName == fieldName)
                {
                    DrawProgressBar(e, warningValue, lessColor, greaterColor);
                    e.Handled = true;
                    DrawEditor(e);
                }
            };
        }

        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            //此事件不能删除，否则无法刷新进度条          
        }

        static void DrawProgressBar(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e, int warningValue = 50, Brush lessColor = null, Brush greaterColor = null)
        {
            //decimal percent = e.CellValue == null ? 0m : (decimal)e.CellValue;
            decimal percent;
            if (e.CellValue == DBNull.Value)
            {
                percent = 0;
            }
            else
            {
                percent = (decimal)e.CellValue;
            }

            int width = (int)(percent * e.Bounds.Width);
            //int width = (int)(percent * e.Bounds.Width) / 100;

            Rectangle rect = new Rectangle(e.Bounds.X, e.Bounds.Y, width, e.Bounds.Height);
            Brush b = Brushes.Green;

            if (greaterColor != null)
            {
                b = greaterColor;
            }

            if (percent * 100 < warningValue )
            //if (percent < warningValue)
                {
                if (lessColor == null)
                {
                    b = Brushes.Red;
                }
                else
                {
                    b = lessColor;
                }
            }
            e.Graphics.FillRectangle(b, rect);
        }

        static void DrawEditor(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            GridCellInfo cell = e.Cell as GridCellInfo;

            Point offset = cell.CellValueRect.Location;
            BaseEditPainter pb = cell.ViewInfo.Painter as BaseEditPainter;
            AppearanceObject style = cell.ViewInfo.PaintAppearance;

            if (!offset.IsEmpty)
                cell.ViewInfo.Offset(offset.X, offset.Y);
            try
            {
                pb.Draw(new ControlGraphicsInfoArgs(cell.ViewInfo, e.Cache, cell.Bounds));
            }
            finally
            {
                if (!offset.IsEmpty)
                {
                    cell.ViewInfo.Offset(-offset.X, -offset.Y);
                }
            }
        }

        //GRIDVIEW页脚汇总设置
        private void setTotalSum()
        {
            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "计数：";
            if (gridView1.Columns.Contains(gridView1.Columns["负责"]))
            {
                gridView1.Columns["负责"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                gridView1.Columns["负责"].SummaryItem.DisplayFormat = "{0:N0}";
                // this.gridView1.Columns["负责"].Width = 80;
            }
        }

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 0;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 60;
        }

    }
}